layui.use(['laydate', 'layer', 'form', 'table', 'configs', 'template', 'excel', 'util', 'formSelects'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        template = layui.template,
        config = layui.configs,
        excel = layui.excel,
        util = layui.util,
        formSelects = layui.formSelects;
    var tableRender = null, filterObj = {};
    var flag = 0, limit = 10, total = 0, curr = 1;
    initAll();

    function initAll() {
        initDate();
        getArea();
    }

    //获取区域
    function getArea() {
        $.ajax({
            url: config.motorBaseUrl + "/area_info/select/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    $(".areaMenu").html(template("motor-areas-tpl", result));
                    if(flag === 0){
                        form.val('paramChart',{
                            'areaId': result.data[0].areaId
                        });
                    }
                    form.render('select');
                    var areaId = $(".areaMenu option:checked").val();
                    getMotors(areaId);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //监听区域选择
    form.on('select(areaMenu)', function (data) {
        flag = 1;
        $(".motorMenu").html("");
        areaId = data.value;
        getMotors(areaId);
    });

    // 查马达
    function getMotors(areaId) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_motors/selectMortor/v1.0",
            type: "post",
            datatype: "json",
            data: {
                areaId: areaId
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    $(".motorMenu").html(template("motors-tpl", result));
                    formSelects.render('select-motor');
                    formSelects.btns('select-motor', ['select', 'remove'], {show: '', space: '10px'});
                    formSelects.value('select-motor', 'val');
                    if(flag === 0){
                        $(".icon-quanxuan").click();
                        $(".searchBtn").click()
                    }
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    //监听所选马达
    // var motorsTitle = [];
    // var motorsId = [];
    // form.on('checkbox(devices)', function (data) {
    //     var title = $(data.elem).attr("title");
    //     if (data.elem.checked) {
    //         motorsTitle.push(title);
    //         motorsId.push(data.value);
    //     } else {
    //         motorsTitle = motorsTitle.filter(function (item) {
    //             return item != title;
    //         });
    //         motorsId = motorsId.filter(function (item) {
    //             return item != data.value;
    //         });
    //     }
    //     var title = motorsTitle.join(",");
    //     $(".optval").attr("value", title);
    //     $(".optval").attr("motorsId", motorsId);
    // });

    function initDate() {
        laydate.render({
            elem: '#startDate',
            value: new Date(new Date().toLocaleDateString()), // 当天0点
            format: 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime',
            max: formatDate()
        });
        laydate.render({
            elem: '#endDate',
            value: new Date(),
            format: 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime',
            max: formatDate(),
            // ready: function (date) {
            //     $(".layui-laydate .layui-laydate-footer").on("click", "span.laydate-btns-time", function () {
            //         var hourLi = $(this).parents(".layui-laydate").find('.laydate-time-show .laydate-time-list > li:nth-child(2)');
            //         hourLi.nextAll().remove();
            //         $(this).parents(".layui-laydate").find('.laydate-time-show .laydate-time-list > li').css("width", "50%");
            //     });
            // }
        });
    };

    //查询
    $(".searchBtn").click(function () {
        var s = util.toDateString($('#startDate').val(), 'yyyy-MM');
        var e = util.toDateString($('#endDate').val(), 'yyyy-MM');
        form.on('submit(search)', function (data) {
            if(s === e){
                filterObj = Object.assign({}, data.field);
                renderTable(data.field);
            }else{
                layer.alert('不能跨月查询');
            }
            return false;
        });
    });

    //渲染表格
    function renderTable(data) {
        tableRender = table.render({
            elem: '.reportTable'
            , id: "motorRecord"
            , url: config.motorBaseUrl + "/mo_data_rec/select/v1.0"
            , method: 'post'
            , where: data
            ,request: {
                pageName: 'curr' //当前页码的参数名称，默认：page
            }
            , parseData: function (res) { //res 即为原始返回的数据
                total = res.data.total;
                return {
                    "code": res.stateCode, //解析接口状态
                    "msg": res.stateMsg, //解析提示文本
                    "count": res.data.total,
                    "data": res.data.data
                }
            }
            // , data: data
            , cols: [[
                {field: 'areaName', title: '区域名称'}
                , {field: 'moName', title: '马达位置'}
                , {field: 'recTime', title: '测量时间', width: 170, templet: '<div>{{ layui.util.toDateString(d.recTime) }}</div>'}
                , {field: 'rockData', title: '振动烈度'}
                , {
                    field: 'upperLimit',
                    title: '振动烈度上限',
                    templet: '<div>{{ d.upperLimit == -1? "未启用" : d.upperLimit}}</div>'
                }
                , {
                    field: 'lowerLimit',
                    title: '振动烈度下限',
                    templet: '<div>{{ d.lowerLimit == -1? "未启用" : d.lowerLimit}}</div>'
                }
            ]]
            ,page: {
                layout: ['prev', 'page', 'next','count','skip','limit'] //自定义分页布局
                ,groups: 1 //只显示 1 个连续页码
                ,first: false //不显示首页
                ,last: false //不显示尾页
                , limits: [10, 20, 50, 100, 500]
            }
            , limit: limit
            , loading: true
        });
    }

    //导出
    $(".exportBtn").on("click", function () {
        filterObj.curr = 1;
        filterObj.limit = total;
        var filename = '马达振动记录' + $('#startDate').val() + '-' + $('#endDate').val() + '.xlsx';
        // 重新请求，获取全部数据
        $.ajax({
            url: config.motorBaseUrl + "/mo_data_rec/select/v1.0",
            dataType: 'json',
            type: "post",
            data: filterObj,
            beforeSend: function(){
                $(".exportBtn").addClass('layui-btn-disabled')
            },
            success: function(res) {
                var data = res.data.data;
                var exportData = []; // 需导出的数据
                var colarr = tableRender.config.cols[0]; // 页面table的表头
                var head = {}; // excel的表头
                for(var i=0;i<colarr.length;i++){
                    head[colarr[i].field] = colarr[i].title;
                }
                // 循环全部数据，按表头取出所需的字段值
                data.forEach(function(item){
                    var obj = {};
                    for(var k in head){
                        obj[k] = item[k];
                        if(k == 'recTime'){
                            obj[k] = util.toDateString(item[k])
                        }
                        if(k == 'upperLimit'){
                            obj[k] = item[k] == -1 ? '未启用' :  item[k]
                        }
                        if(k == 'lowerLimit'){
                            obj[k] = item[k] == -1 ? '未启用' :  item[k]
                        }
                    }
                    exportData.push(obj);
                });
                exportData.unshift(head);
                excel.exportExcel({
                    sheet1: exportData
                }, filename, 'xlsx');
            },
            complete: function () {
                $(".exportBtn").removeClass('layui-btn-disabled')
            }
        });
    });

    //年月日时 分秒为00 2019-09-24 08:00:00
    function hourZero(date) {
        var date = date || new Date();
        var Y = date.getFullYear();
        var M = date.getMonth() + 1;
        M = M < 10 ? '0' + M : M;
        var D = date.getDate();
        D = D < 10 ? '0' + D : D;
        var h = date.getHours();
        h = h < 10 ? '0' + h : h;
        var m = date.getMinutes();
        m = m < 10 ? '0' + m : m;
        return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':00';
    }
});